package br.com.amadeus.android.activities.course.task;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TimePicker;
import br.com.amadeus.android.activities.home.R;
import br.com.amadeus.android.business.FacadeAmadeusDroid;
import br.com.amadeus.android.entities.Action;
import br.com.amadeus.android.entities.Course;
import br.com.amadeus.android.entities.CourseUser;
import br.com.amadeus.android.entities.Goal;
import br.com.amadeus.android.entities.Resource;
import br.com.amadeus.android.entities.Task;
import br.com.amadeus.android.util.Util;

public class FormTaskActivity extends Activity{
	
	FacadeAmadeusDroid facede = FacadeAmadeusDroid.getInstance(this);
	
	protected static final String CATEGORIA = "curso";
	
	private Intent itHomeCourse;
	
	List<String> resourceList;
	List<String> actionList;
	List<String> goalList;
	
	List<Goal> goals;
	List<Action> actions;
	List<Resource> resources;
	
	private Button btnSave;
	private Button btnCancel;
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		finish();
	}


	private Button mPickDate;
	private int mYear;
	private int mMonth;
	private int mDay;
	static final int DATE_DIALOG_ID = 0;
	
	private Button mPickDateFinish;
	private int mYearFinish;
	private int mMonthFinish;
	private int mDayFinish;
	static final int DATE_DIALOG__FINAL_ID = 2;
	
	private Button mPickTime;
	private int mHour;
	private int mMinute;
	static final int TIME_DIALOG_ID = 1;
	
	private Button mPickTimeFinish;
	private int mHourFinish;
	private int mMinuteFinish;
	static final int TIME_DIALOG_FINAL_ID = 3;
	
	StringBuilder sbBeginDate = new StringBuilder();
	StringBuilder sbEndDate = new StringBuilder();
	StringBuilder sbBeginTime = new StringBuilder();
	StringBuilder sbEndTime = new StringBuilder();
	
	Spinner spinnerResources;
	Spinner spinnerActions;
	
	private int goal_id;
	private int course_id;
	private int task_id = 0;
	
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_task);
		
		initComponents();
		
		spinnerResources = (Spinner) findViewById(R.id.spResources);
		spinnerActions = (Spinner) findViewById(R.id.spActions);
								
		Bundle gotBasket = getIntent().getExtras();
		
		itHomeCourse = new Intent("LIST_TASK");
	    Bundle taskBasket = new Bundle();
	    taskBasket.putInt("course_id", course_id);
	    taskBasket.putInt("goal_id", goal_id);
	    itHomeCourse.putExtras(taskBasket);
										
		task_id = gotBasket.getInt("task_id");
		if (task_id == 0) {
					
			goal_id = gotBasket.getInt("goal_id");
		    course_id = gotBasket.getInt("course_id");
		    fillResources();
		    fillSpinners();
		    fillFormTask();
		    
		}else{
			
			Task task = facede.getTask(task_id);
			goal_id = task.getGoal().getId();
			Goal goal = facede.getGoal(goal_id);
			CourseUser courseUser = facede.getCourseUserById(goal.getCourseUser().getId());
			Course course = facede.getCourseByAmadeusId(courseUser.getCourse().getId());
			course_id = course.getId();
			fillResources();
			updateFormTask(task);
			
		}
				               						
		btnSave.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View v) 
			{
				Resource resource = (Resource)spinnerResources.getSelectedItem();
				Goal goal = new Goal(goal_id);
				Action action = (Action)spinnerActions.getSelectedItem();
				
				String date1 = sbBeginDate.toString()+sbBeginTime.toString();
				String date2 = sbEndDate.toString()+sbEndTime.toString();
				if(this.validateDates(date1, date2)){
					Task task = new Task(task_id,date1,date2, false, action, resource, goal);
					facede.insertTask(task);
					
					itHomeCourse.putExtra("course_id", course_id);
					itHomeCourse.putExtra("goal_id", goal_id);
					startActivity(itHomeCourse);
				}
				
				
			}

			private boolean validateDates(String date1, String date2) {
				GregorianCalendar d1 = Util.stringDatetoGregorianCalendar(date1);
				GregorianCalendar d2 = Util.stringDatetoGregorianCalendar(date2);
				if (d1.after(d2)) {
					AlertDialog.Builder dialog = new AlertDialog.Builder(FormTaskActivity.this);
					dialog.setMessage("A data de fim é antes da inicial. Por favor, verifique.");
					dialog.setNeutralButton("OK", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							try {
								this.finalize();
							} catch (Throwable e) {
								e.printStackTrace();
							}
							
						}
					});
					dialog.show();
					return false;
				}
				return true;
			}
		});
		
		
		btnCancel.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View v) 
			{				
				finish();
			}
		});
		
		// add a click listener to the button
		mPickDate.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}
		});
		
		//-------------------------------------------------------------------------------------------//

		//-------------------------------------------------------------------------------------------//
		//display data final

		// add a click listener to the button
		mPickDateFinish.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(DATE_DIALOG__FINAL_ID);
			}
		});

		
		//-------------------------------------------------------------------------------------------//
		
		//-------------------------------------------------------------------------------------------//		
		//display de horas inicial

		
		// add a click listener to the button
		mPickTime.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(TIME_DIALOG_ID);
			}
		});
				
		//-------------------------------------------------------------------------------------------//

		//-------------------------------------------------------------------------------------------//		
		//display de horas final

		// add a click listener to the button
		mPickTimeFinish.setOnClickListener(new View.OnClickListener() 
		{
			public void onClick(View v) {
				showDialog(TIME_DIALOG_FINAL_ID);
			}
		});

		//-------------------------------------------------------------------------------------------//
		
	}

	private void fillResources() {
		
		if (course_id == 0) {
			Goal goal = facede.getGoalFull(goal_id);
			//Log.i("OLHAAA: ", " "+goal.getCourseUser().getId());
			Course course = facede.getCourseByAmadeusId(goal.getCourseUser().getId());
			course_id = course.getId();
		} 
		this.resources = this.facede.getResourceByCourse(course_id);
		this.goals = this.facede.getAllGoalByCourse(course_id);
	    this.actions = this.facede.getAllActions();
		
	}

	private void fillSpinners() {
			    
	    if(!resources.isEmpty()){
	        ArrayAdapter<Resource> adapter = new ArrayAdapter<Resource>(this,android.R.layout.simple_dropdown_item_1line, resources );
	        spinnerResources.setAdapter(adapter);
		}else{
	        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
			dialog.setMessage("Não existem recursos de aprendizagem! Peça para o professor Cadastar no Amadeus Web.");
			dialog.setNeutralButton("OK", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					try {
						this.finalize();
					} catch (Throwable e) {
						e.printStackTrace();
					}
					
				}
			});
			dialog.show();
		}
		
		if(!actions.isEmpty()){
	        ArrayAdapter<Action> adapter2 = new ArrayAdapter<Action>(this,android.R.layout.simple_dropdown_item_1line, actions );
	        spinnerActions.setAdapter(adapter2);
		}else{
			AlertDialog.Builder dialog = new AlertDialog.Builder(this);
			dialog.setMessage("Não existem Ações pré-cadastradas! Insira no panel de Configurações do sistema.");
			dialog.setNeutralButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					try {
						this.finalize();
					} catch (Throwable e) {
						e.printStackTrace();
					}
					
				}
			});
			dialog.show();
		}
		
	}

	private void initComponents() {
						
		btnSave = (Button)findViewById(R.id.imgBtnSave);
		btnCancel = (Button)findViewById(R.id.imgBtnCancel);
		
		mPickDate = (Button) findViewById(R.id.pickDate);
		
		mPickDateFinish = (Button) findViewById(R.id.pickDateFinal);
		
		mPickTime = (Button) findViewById(R.id.pickTime);
		
		mPickTimeFinish = (Button) findViewById(R.id.pickTimeFinal);
		
	}

	private void fillFormTask() {
		// get the current date
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
		
		// Display de datas
		updateDisplayDates();
		
		// get the current date
		final Calendar c2 = Calendar.getInstance();
		mYearFinish = c2.get(Calendar.YEAR);
		mMonthFinish = c2.get(Calendar.MONTH);
		mDayFinish = c2.get(Calendar.DAY_OF_MONTH);

		updateDisplayDatesFinal();
		
		// get the current time
		final Calendar c1 = Calendar.getInstance();
		mHour = c1.get(Calendar.HOUR_OF_DAY);
		mMinute = c1.get(Calendar.MINUTE);
		
		updateDisplayTimer();
		
		final Calendar c3 = Calendar.getInstance();
		mHourFinish = c3.get(Calendar.HOUR_OF_DAY);
		mMinuteFinish = c3.get(Calendar.MINUTE);

		// display the current date
		updateDisplayTimerFinal();
		
	}

	private void updateFormTask(Task task) {
		//Preencher Resource
		Resource res = facede.getResource(task.getResource().getId());
		List<Resource> listRes = new ArrayList<Resource>();
		listRes.add(res);
		for (Resource r : this.resources) {
			if (r.getId() != res.getId()) {
				listRes.add(r);
			}
		}
		
		ArrayAdapter<Resource> adapter = new ArrayAdapter<Resource>(this,android.R.layout.simple_dropdown_item_1line, listRes );
	    spinnerResources.setAdapter(adapter);
	     
	    //Preencher Actions
	    Action act = facede.getAction(task.getAction().getId());
	    List<Action> listAct = new ArrayList<Action>();
	    listAct.add(act);
	    for (Action a : this.actions) {
			if (a.getId() != act.getId()) {
				listAct.add(a);
			}
		}
	    ArrayAdapter<Action> adapter2 = new ArrayAdapter<Action>(this,android.R.layout.simple_dropdown_item_1line, listAct );
	    spinnerActions.setAdapter(adapter2);
	    
	 // get the current date
		final Calendar c = Calendar.getInstance();
		Date initialDate = Util.getDate(task.getBeginDate(), Util.FORMATO_DATA_UI);
		c.setTime(initialDate);
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
		
		// Display de datas
		updateDisplayDates();
		
		// get the current date
		final Calendar c2 = Calendar.getInstance();
		Date finalDate = Util.getDate(task.getEndDate(), Util.FORMATO_DATA_UI);
		c2.setTime(finalDate);
		mYearFinish = c2.get(Calendar.YEAR);
		mMonthFinish = c2.get(Calendar.MONTH);
		mDayFinish = c2.get(Calendar.DAY_OF_MONTH);

		updateDisplayDatesFinal();
		
		// get the current time
		final Calendar c1 = Calendar.getInstance();
		c1.setTime(initialDate);
		mHour = c1.get(Calendar.HOUR_OF_DAY);
		mMinute = c1.get(Calendar.MINUTE);
		
		updateDisplayTimer();
		
		final Calendar c3 = Calendar.getInstance();
		c3.setTime(finalDate);
		mHourFinish = c3.get(Calendar.HOUR_OF_DAY);
		mMinuteFinish = c3.get(Calendar.MINUTE);

		// display the current date
		updateDisplayTimerFinal();
	}

	//atualiza os dados do calendário
	private void updateDisplayDates() 
	{
		String zeroMes = "";
		String zeroDia = "";

		if(mMonth < 10)
		{
			zeroMes = "0";
		}
		if(mDay < 10)
		{
			zeroDia = "0";
		}

		//atualizando o lable do botão
		//
		
		StringBuilder sbBeginDateTemp = new StringBuilder();
		sbBeginDateTemp.append(zeroDia).append(mDay).append("/")
		.append(zeroMes).append(mMonth + 1).append("/")
		.append(mYear).append(" ");
		sbBeginDate.replace(0, 12, sbBeginDateTemp.toString());
		mPickDate.setText(sbBeginDate);
	}


	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() 
	{
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) 
		{
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			updateDisplayDates();
		}
	};


	private void updateDisplayTimer() 
	{
		String zeroHora = "";
		String zeroMinuto = "";

		if(mHour < 10)
		{
			zeroHora = "0";
		}

		if(mMinute < 10)
		{
			zeroMinuto = "0";
		}
		StringBuilder sbBeginTimeTemp =  new StringBuilder();
		sbBeginTimeTemp.append(zeroHora).append(mHour).append(":")
		.append(zeroMinuto).append(mMinute);
		sbBeginTime.replace(0, 5, sbBeginTimeTemp.toString());
		mPickTime.setText(sbBeginTime.toString());
	}

	private static String pad(int c) 
	{
		if (c >= 10)
			return String.valueOf(c);
		else
			return "0" + String.valueOf(c);
	}

	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() 
	{
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) 
		{
			mHour = hourOfDay;
			mMinute = minute;
			updateDisplayTimer();
		}
	};

	//-------------------------------------------------------------------------------------------//		
	//display de data final

	private void updateDisplayDatesFinal() 
	{
		String zeroMes = "";
		String zeroDia= "";

		if(mMonthFinish < 10)
		{
			zeroMes = "0";
		}
		if(mDayFinish < 10)
		{
			zeroDia = "0";
		}
		
		//atualizando o lable
		StringBuilder sbEndDateTemp = new StringBuilder();
		sbEndDateTemp.append(zeroDia).append(mDayFinish).append("/")
		.append(zeroMes).append(mMonthFinish + 1).append("/")
		.append(mYearFinish).append(" ");
		sbEndDate.replace(0, 12, sbEndDateTemp.toString());
		mPickDateFinish.setText(sbEndDate);
	}


	private DatePickerDialog.OnDateSetListener mDateSetListenerFinal = new DatePickerDialog.OnDateSetListener() 
	{
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) 
		{
			mYearFinish = year;
			mMonthFinish = monthOfYear;
			mDayFinish = dayOfMonth;
			updateDisplayDatesFinal();
		}
	};

	//-------------------------------------------------------------------------------------------//		


	//-------------------------------------------------------------------------------------------//		
	//display timer final
	private void updateDisplayTimerFinal() 
	{
		String zeroHora = "";
		String zeroMinuto = "";

		if(mHourFinish < 10)
		{
			zeroHora = "0";
		}

		if(mMinuteFinish < 10)
		{
			zeroMinuto = "0";
		}
		
		StringBuilder sbEndTimeTemp =  new StringBuilder();
		sbEndTimeTemp.append(zeroHora).append(mHourFinish).append(":")
		.append(zeroMinuto).append(mMinuteFinish);
		sbEndTime.replace(0, 5, sbEndTimeTemp.toString());
		mPickTimeFinish.setText(sbEndTime.toString());
	}


	private TimePickerDialog.OnTimeSetListener mTimeSetListenerFinal = new TimePickerDialog.OnTimeSetListener() 
	{
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) 
		{
			mHourFinish = hourOfDay;
			mMinuteFinish = minute;
			updateDisplayTimerFinal();
		}
	};


	@Override
	protected Dialog onCreateDialog(int id) 
	{
		switch (id) 
		{
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);

		case DATE_DIALOG__FINAL_ID:
			return new DatePickerDialog(this, mDateSetListenerFinal, mYearFinish, mMonthFinish, mDayFinish);

		case TIME_DIALOG_ID:
			return new TimePickerDialog(this, mTimeSetListener,mHour, mMinute, false);

		case TIME_DIALOG_FINAL_ID:
			return new TimePickerDialog(this, mTimeSetListenerFinal,mHourFinish, mMinuteFinish, false);
		}

		return null;
	}


	
}
